<template>
    <el-card shadow="never" class="border-0">
        <!-- 搜索 -->
        <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
            <el-row :gutter="20">
                <el-col :span="5" :offset="0">
                    <el-form-item label="项目名称">
                        <el-input v-model="searchForm.projectName" placeholder="项目名称" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <div class="flex items-center justify-end">
                        <el-button type="primary" @click="getData">搜索</el-button>
                        <el-button @click="resetSearchForm">重置</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-form>

        <!-- 新增|刷新 -->
        <div class="flex items-center justify-between mb-4">
            <el-button type="primary" size="small" @click="handleCreate">新增</el-button>
            <el-tooltip effect="dark" content="刷新数据" placement="top">
                <el-button text @click="getData">
                    <el-icon :size="20">
                        <Refresh />
                    </el-icon>
                </el-button>
            </el-tooltip>
        </div>

        <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
            <!-- <el-table-column label="项目ID" prop="projectId"></el-table-column> -->
            <el-table-column label="项目名称" align="center" prop="projectName" show-overflow-tooltip></el-table-column>
            <el-table-column label="项目编号" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.projectNo == null ? "-" : row.projectNo }}
                </template>
            </el-table-column>

            <el-table-column label="项目类型" align="center">
                <template #default="{ row }">
                    {{ formatProjectStatus(row.projectStatus) }}
                </template>
            </el-table-column>

            <el-table-column label="客户名称" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.customerName }}
                </template>
            </el-table-column>

            <el-table-column label="开始时间" align="center">
                <template #default="{ row }">
                    {{ row.startTime == null ? "-" : row.startTime }}
                </template>
            </el-table-column>

            <el-table-column label="结束时间" align="center">
                <template #default="{ row }">
                    {{ row.endTime == null ? "-" : row.endTime }}
                </template>
            </el-table-column>

            <el-table-column label="操作" width="250" align="center">
                <template #default="scope">
                    <div>
                        <!-- <el-button type="primary" size="small" text @click="clickWorkOrderBtn(scope.row)">详情</el-button> -->
                        <el-button type="primary" size="small" text @click="handleEdit(scope.row)">编辑</el-button>


                        <el-popconfirm title="是否要删除该项目？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="handleDelete(scope.row.projectId)">
                            <template #reference>
                                <el-button text type="primary" size="small">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <div class="flex items-center justify-center mt-5">
            <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
                :page-size="limit" @current-change="getData" />
        </div>

        <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
            <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
                <el-form-item label="项目名称" prop="projectName">
                    <el-input v-model="form.projectName" placeholder="项目名称" maxlength="30" show-word-limit></el-input>
                </el-form-item>

                <el-form-item label="客户公司">
                    <el-button plain @click="dialogTableVisible_customer = true">
                        {{ !form.customerName ? '选择公司' : form.customerName }}
                    </el-button>
                </el-form-item>

                <el-form-item label="项目编号">
                    <el-input v-model="form.projectNo" placeholder="项目编号" maxlength="20" show-word-limit></el-input>
                </el-form-item>

                <el-form-item label="项目类型">
                    <el-select v-model="form.projectStatus" filterable placeholder="请选择项目类型">
                        <el-option v-for="item in projectStatuses" :key="item.code" :label="item.description"
                            :value="item.code">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker v-model="form.startTime" type="date" placeholder="开始时间" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD">
                    </el-date-picker>

                </el-form-item>

                <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker v-model="form.endTime" type="date" placeholder="结束时间" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD">
                    </el-date-picker>
                </el-form-item>

            </el-form>
        </FormDrawer>
    </el-card>

    <!-- 选择客户（公司） -->
    <!-- <el-dialog v-model="dialogTableVisible_customer" title="选择公司" width="70%" align-center>
        <SelectCompany v-if="dialogTableVisible_customer" :showSelection="true" :selectedCompanyId="form.customerId"
            @getCheckedCompany="getCheckedCompany" />
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="dialogTableVisible_customer = false">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog> -->

    <!-- 选取客户dialog -->
    <SystemDialog title="选择客户" 
        :visible="dialogTableVisible_customer" 
        :height="50" 
        :width="70"
        @on-close="dialogTableVisible_customer = false" 
        @on-confirm="dialogTableVisible_customer = false">
        <template v-slot:content>
            <SelectCompany v-if="dialogTableVisible_customer" :showSelection="true"
                :selectedCompanyId="form.customerId" @getCheckedCompany="getCheckedCompany" />
        </template>
    </SystemDialog>

</template>
<script setup>
import { ref, reactive, computed, onMounted } from "vue"
import FormDrawer from "~/components/FormDrawer.vue";
import { api_project_constant } from "~/api/ordersApi"
import { toast } from "~/composables/util"
import { api_project_add, api_project_list, api_project_update, api_project_delete } from "~/api/projectApi";
import SelectCompany from "~/components/select-company.vue";
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import SystemDialog from "~/components/SystemDialog.vue";


//store存储
const store = useStore()
// 全局路由
const router = useRouter()

// 分页
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)

const searchForm = reactive({
    projectName: "",
    projectId: "",
    customerId: "",
    projectStatus: null,

    page: currentPage.value,
    size: limit.value,
})
const resetSearchForm = () => {
    searchForm.projectName = ""
    searchForm.projectId = ""
    searchForm.customerId = ""
    searchForm.projectStatus = null
    getData()
}

const tableData = ref([])
const loading = ref(false)
const projectTypes = ref([])
const projectStatuses = ref([])

// 表单部分
const formDrawerRef = ref(null)
const formRef = ref(null)
const form = reactive({
    projectId: null,
    projectName: "",
    projectNo: "",
    projectDescription: "",
    projectLocationId: null,
    //公司id（用于业务）
    customerId: null,
    //公司名称（用于显示）
    customerName: null,
    projectStatus: null,
    startTime: null,
    endTime: null,

    //位置信息（方便做不为空校验）
    formattedAddress: null,
    locationCreateDto: {
        latitude: null,
        longitude: null,
        locationType: "1",
        formattedAddress: "",
        adcode: "",
        country: "",
        province: "",
        city: "",
        district: "",
        township: "",

    }
})

const rules = {
    projectName: [
        { required: true, message: '项目名称不能为空', trigger: 'change' }
    ],
    // projectDescription: [
    //   { required: true, message: '项目描述不能为空', trigger: 'change' }
    // ],
    customerId: [
        { required: true, message: '客户公司不能为空', trigger: 'blur' }
    ],
    // startTime: [
    //   { required: true, message: '开始时间不能为空', trigger: 'change' }
    // ],
    // endTime: [
    //   { required: true, message: '结束时间不能为空', trigger: 'change' }
    // ],
    formattedAddress: [
        { required: true, message: '位置信息不能为空', trigger: 'change' }
    ]
}
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "新增")
const dialogTableVisible_customer = ref(false)
const checkedCustomer = ref(null)
//项目开展位置信息
const address = ref("点击设置位置");

// 生命周期函数
onMounted(() => {
    //获取字典数据
    getSelectData()

    //获取table数据
    getData()
})


// 获取选择的客户
function getCheckedCompany(data) {
    //console.log('checked customer: ', data)
    if (data != null) {
        form.customerId = data.id
        form.customerName = data.name
        checkedCustomer.value = data
        //清空“客户公司”校验信息
        formRef.value.clearValidate(['customerId'])
    }
}

// 获取订单状态
function getSelectData() {
    api_project_constant().then(res => {
        console.log('project constant: ', res)
        projectTypes.value = res?.projectTypes
        projectStatuses.value = res?.projectStatuses
    })
}


const formatProjectStatus = (projectStatus) => {
    return projectStatuses.value.find(x => x.code == projectStatus)?.description || projectStatus
}


// 获取数据
function getData(p = null) {
    if (typeof p == "number") {
        currentPage.value = p
    }

    loading.value = true
    searchForm.page = currentPage.value
    api_project_list(searchForm)
        .then(res => {
            //console.log('project list', res)
            tableData.value = res.records.map(o => {
                o.statusLoading = false
                return o
            })
            total.value = res.total
            currentPage.value = res.current
            // roles.value = res.roles
        })
        .finally(() => {
            loading.value = false
        })
}

// 删除项目
function handleDelete(projectId) {
    api_project_delete(projectId).then(res => {
        toast("删除成功")
        getData()
    })
}

const handleSubmit = () => {
    formRef.value.validate((valid) => {
        if (!valid) return

        formDrawerRef.value.showLoading()

        let reqBody = { ...form }
        //console.log('create project req body: ', reqBody)
        //console.log('edit Id :', editId.value)
        const fun = editId.value
            ? api_project_update(editId.value, reqBody)
            : api_project_add(reqBody);


        fun.then(res => {
            toast(drawerTitle.value + "成功")
            // 修改刷新当前页，新增刷新第一页
            getData(editId.value ? false : 1)
            formDrawerRef.value.close()
        }).finally(() => {
            formDrawerRef.value.hideLoading()
        })

    })
}

  // 编辑
  const handleEdit = (row) => {
    editId.value = row.projectId
    resetForm(row)
    formDrawerRef.value.open()
  }

// 重置表单
function resetForm(row = false) {
    if (formRef.value) formRef.value.resetFields()
    if (row) {
        for (const key in form) {
            form[key] = row[key]
        }
    }
}

// 新增
const handleCreate = () => {
    editId.value = 0
    resetForm({
        projectId: null,
        projectName: "",
        projectNo: "",
        projectDescription: "",
        projectLocationId: null,
        //公司id（用于业务）
        customerId: null,
        //公司名称（用于显示）
        customerName: null,
        projectStatus: null,
        startTime: null,
        endTime: null,
        formattedAddress: null,
        locationCreateDto: {
            latitude: null,
            longitude: null,
            locationType: "1",
            formattedAddress: "",
            adcode: "",
            country: "",
            province: "",
            city: "",
            district: "",
            township: "",

        }
    })
    address.value = "点击设置位置"
    checkedCustomer.value = null
    if (formRef.value) formRef.value.resetFields()
    formDrawerRef.value.open()
}

// 点击工单按钮
const clickWorkOrderBtn = (row) => {
    store.commit("SetProjectId", row.projectId)

    //跳转界面
    router.push({
        path: '/projectDetails',
    });
}
</script>